package com.yuanian.ecsplus.scan;

import com.yuanian.ecsplus.annotation.BusinessObject;
import com.yuanian.ecsplus.cache.CacheManager;
import com.yuanian.ecsplus.exception.EcsPlusException;
import com.yuanian.ecsplus.model.entity.BaseModel;
import com.yuanian.ecsplus.model.vo.BaseVoModel;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
 * model扫描器，在启动前加入到缓存中
 */
@Component
public class ModelScanner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        ClassPathScanningCandidateComponentProvider p = new ClassPathScanningCandidateComponentProvider(true);
        p.addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                try {
                    Class clz = Class.forName(metadataReader.getClassMetadata().getClassName());
                    if (clz.isAnnotationPresent(BusinessObject.class)) {
                        if (BaseModel.class.isAssignableFrom(clz)) {
                            CacheManager.getInstance().getMetaEntity(clz);
                        } else if (BaseVoModel.class.isAssignableFrom(clz)) {
                            CacheManager.getInstance().getMetaVo(clz);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    throw new EcsPlusException(e.getCause());
                }
                return false;
            }
        });
        p.findCandidateComponents("com.yuanian.dp");
    }
}
